package ua.epam.muzalevskiy.traction.commands;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ua.epam.muzalevskiy.traction.configuretion.PagePathConfigurer;
import ua.epam.muzalevskiy.traction.dao.DaoFactory;
import ua.epam.muzalevskiy.traction.dao.RouteDao;
import ua.epam.muzalevskiy.traction.route.Route;
import ua.epam.muzalevskiy.traction.route.Stop;

/**
 * <code>GenerateScheduleCommand</code> class is the <code>Command</code> 
 * interface implementation, that realized <code>Command</code> pattern.
 * Current class encapsulate action of generating page in which user can
 * see the schedule of selected route.
 *
 * @author Muzalevskiy Vitaliy
 * @see Command
 * @see Route
 * @see Stop
 * @see RouteDao
 */
public class GenerateScheduleCommand implements Command {

    private static DaoFactory factory = new DaoFactory();
    private RouteDao routeDao = factory.getRouteDao();
    private static final String PARAM_NAME_ROUTE = "route";
    private static final String ATTRIBUTE_NAME_AVARAGE_INTERVAL = "avarage_interval";
    private static final String ATTRIBUTE_NAME_STOPS = "stops";

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String page;
        String routeNumber = request.getParameter(PARAM_NAME_ROUTE);
        Route route = routeDao.selectRouteByNumber(routeNumber);
        List<Stop> stopList = route.getStops();
        
        String[] stops = new String[stopList.size()];
        for(int i = 0; i < stopList.size(); i++){
            stops[i] = (i + 1) + ". " + stopList.get(i).getName();
        }
        request.setAttribute(ATTRIBUTE_NAME_AVARAGE_INTERVAL,
                route.getAvarageIntervalTime());
        request.setAttribute(ATTRIBUTE_NAME_STOPS, stops);
        page = PagePathConfigurer.getInstance()
                .getProperty(PagePathConfigurer.SCHEDULE_RESULT_PAGE);
        return page;
    }


}
